import { BUNDLE_TYPE_ENUM, EVENT_NAME_ENUM } from "../../base/EnumIndex";
import { Tools } from "../../common/Tools";
import TouchScale from "../../item/Common/TouchScale";
import LvItem from "../../LvItem";
import { AudioManager1 } from "../../manager/AudioManager1";
import { EventManager } from "../../manager/EventManager";
import { UIManager } from "../../manager/UIManager";
import LevelPre_23 from "./LevelPre_23";

const { ccclass, property } = cc._decorator;

let ANSWER: Array<Array<[string, boolean, string, string]>> = [];
let QUESION = [];

let WRONG_NUM = 3;

enum GAME_STATE {
    RUNNING, WIN, FAIL
}

@ccclass
export default abstract class Level_23_Base extends cc.Component {
    @property(sp.Skeleton)
    mainSpine: sp.Skeleton = null;
    @property(sp.Skeleton)
    npcSpine: sp.Skeleton = null;
    @property(cc.Node)
    mainTalk: cc.Node = null;
    @property(cc.Node)
    npcTalk: cc.Node = null;

    @property(cc.Node)
    hpNode: cc.Node = null;

    levelPre: LevelPre_23;
    wrongNum: number = 0;

    gameState: GAME_STATE = GAME_STATE.RUNNING;

    NpcAudioId: number = null
    MainAudioId: number = null

    /**是否开启自动答题 */
    autoAnswer = false;
    /**是否选错后按正确答案 */
    answerRight = false;

    /**是否在自动答题中已手动选择 */
    isSelect: boolean = false;
    onLoad() {
        EventManager.ins.on(EVENT_NAME_ENUM.FINISH_INTER_TWEEN, this.finish, this);
    }
    protected onDestroy(): void {
        EventManager.ins.off(EVENT_NAME_ENUM.FINISH_INTER_TWEEN, this.finish, this);
    }
    start() {
        let isAutoAnswerActive = Tools.getStorage('setAutoAnswerActive')
        if (isAutoAnswerActive && isAutoAnswerActive != "false") {
            this.autoAnswer = true;
        } else {
            this.autoAnswer = false;
        }

        let isAnswerRightActive = Tools.getStorage('setAnswerRightActive')
        if (isAnswerRightActive && isAnswerRightActive != "false") {
            this.answerRight = true;
        } else {
            this.answerRight = false;
        }

    }

    initGame() {
        this.levelPre = cc.find("Canvas").getComponentInChildren(LevelPre_23);

        // 适配
        let widthScale = this.levelPre.maskNode.width / this.levelPre.huaNode.width;
        let heightScale = this.levelPre.maskNode.height / this.levelPre.huaNode.height;
        this.levelPre.huaNode.scale = Math.min(widthScale, heightScale);

        if (this.levelPre.huaNode.getComponent(TouchScale)) {
            this.levelPre.huaNode.getComponent(TouchScale).maskNode = this.levelPre.maskNode;
        }

        ANSWER = this.levelPre.interJson.answer;
        QUESION = this.levelPre.interJson.questions;
        WRONG_NUM = this.levelPre.interJson.wrongNum;
        // this.levelPre.playQuestionAnim(false);
        this.levelPre.content.active = false;
        this.randomOrder();
        this.startGame();
    }
    /** 打乱顺序 */
    randomOrder() {
        ANSWER.forEach(i => Tools.aginSortArr(i));
        // cc.log(ANSWER)
    }
    /** 开始一轮游戏 */
    async startGame() {
        this.isSelect = false;
        cc.log("当前第" + this.levelPre.progress + "题")
        UIManager.ins.enabledGameClick(false);
        this.npcTalk.active = true;
        this.npcTalk.getComponent(LvItem).setLabString(QUESION[this.levelPre.progress]);
        this.npcSpine.setAnimation(0, "shuohua", true);
        this.talkAnim();
        this.NpcAudioId = await AudioManager1.playAudio("" + (1 + this.levelPre.progress), 1, BUNDLE_TYPE_ENUM.LEVEL);
        cc.Tween.stopAllByTarget(this.npcTalk);
        let audioTime = cc.audioEngine.getDuration(this.NpcAudioId);
        cc.tween(this.npcTalk).delay(audioTime).call(() => this.npcTalkEnd()).start();
    }
    talkAnim() {
        // 留给子类重写
    }
    npcTalkEnd() {
        this.levelPre.content.active = true;
        this.updateOption();

        this.npcSpine.setAnimation(0, "daiji", true);
        UIManager.ins.enabledGameClick(true);
    }

    /** 更新选项 */
    updateOption() {
        if (!this.levelPre["lbQ"]) return;
        let questions = ANSWER[this.levelPre.progress];
        console.log("questions", questions);

        for (let i = 0; i < questions.length; i++) {
            let optionLbl = this.levelPre["lbQ"][i];
            if (optionLbl) optionLbl.string = questions[i][0];
        }
        this.levelPre.playQuestionAnim();
    }
    /** 点击选项后 处理 */
    finish(finishStr: any) {
        if (typeof finishStr != "string") {
            return;
        }
        if (finishStr.includes("ans")) {
            this.isSelect = true;
            let progress = Number(finishStr.split("_")[2]);
            let answer = Number(finishStr.split("_")[3]);
            this.levelPre.playQuestionAnim(false);
            this.checkAnswer(progress, answer - 1);
        } else if (finishStr === "initGame")
            this.initGame();
    }



    /** 检测答案对错 */
    async checkAnswer(progress: number, answer: number) {
        AudioManager1.stopAudio(this.NpcAudioId)
        let questions = ANSWER[progress];
        let txt = questions[answer][3] || questions[answer][0];
        let isRight = questions[answer][1];
        if (this.autoAnswer || this.answerRight) {
            isRight = true;
        }
        let audio = questions[answer][2];
        let audioUrl = (progress + 1) + "" + audio;

        this.mainTalk.active = true;
        this.mainTalk.getComponent(LvItem).setLabString(txt);
        cc.Tween.stopAllByTarget(this.mainTalk);
        this.mainSpine.setAnimation(0, "shuohua", true);

        this.MainAudioId = await AudioManager1.playAudio(audioUrl, 1, BUNDLE_TYPE_ENUM.LEVEL);
        let audioTime = cc.audioEngine.getDuration(this.MainAudioId);

        let time = this.getDelayTime(isRight);
        cc.tween(this.node).delay(audioTime).call(() => {
            if (!isRight) this.wrongNum += 1;
            this.levelPre.progress++;
            this.updateGameState();
            // cc.log("this.gameState == " + this.gameState, this.wrongNum)

            this.npcTalk.active = false;
            this.mainTalk.active = false
            if (isRight) {
                this.rightAnim();
            } else {
                this.subHp();
                this.wrongAnim();
            }
        }).delay(time).call(() => {
            this.updateGame();
        }).start();
    }
    /** 游戏状态 */
    updateGameState() {
        if (this.wrongNum >= WRONG_NUM) {
            this.gameState = GAME_STATE.FAIL;
        } else if (this.levelPre.progress === ANSWER.length) {
            this.gameState = GAME_STATE.WIN;
        } else {
            this.gameState = GAME_STATE.RUNNING;
        }
    }
    updateGame() {
        switch (this.gameState) {
            case GAME_STATE.RUNNING:
                this.resetAnim();
                this.startGame()
                break;
            case GAME_STATE.WIN:
                this.levelPre.runNodeTween(this.node, this.levelPre.getInterTwForName("winGame").interTween);
                break;
            case GAME_STATE.FAIL:
                this.levelPre.runNodeTween(this.node, this.levelPre.getInterTwForName("overGame").interTween);
                break;
            default:
                break;
        }
    }
    abstract getDelayTime(isRight: boolean): number;
    abstract resetAnim(): void;
    abstract rightAnim(): void;
    abstract wrongAnim(): void;

    /** 掉血量 */
    subHp() {
        let item = this.hpNode.children[WRONG_NUM - this.wrongNum]; //2 1 0
        Tools.setSpriteState(item, 1);
    }

    /** 加血量 */
    addHp() {
        let item = this.hpNode.children[WRONG_NUM - this.wrongNum]; //2 1 0
        Tools.setSpriteState(item, 0);
    }
}